<template>
    <div class="outer">
        <div class="title-d outer-title" :class="themeType">
            <div class="title-d-left">
                {{ dayTimeO }}
            </div>
            <div class="title-d-middle"> 应急就医服务中心</div>
            <div class="title-d-right"> 累计运行时间：{{ dayTimeT }}</div>
        </div>
        <div class="body-d">
            <div class="body-d-left" :class="[themeType]">
                <one-l theme="light" :setting="setting" :refreshState="refreshState" @handleClick="handlePhoneDialog" />
                <two-l theme="light" :key="tabState" :refreshState="refreshState" @view-detail="viewDetail" />
                <three-l :key="tabState" :setting="setting" :refreshState="refreshState" />
            </div>
            <div class="body-d-middle">
                <xian-map
                    :showHospitalList="showHospitalList"
                    :hospitalList="hospitalList"
                    @clearHospitalList="clearHospitalList"
                    :mapOptions="lightMapOption"
                />
            </div>
            <div class="body-d-right" :class="[themeType]">
                <one-r :setting="setting" :refreshState="refreshState" />
                <two-r :key="tabState" :setting="setting" :refreshState="refreshState" />
                <three-r :key="refreshState" />
            </div>
        </div>
        <div class="bottom-d"></div>
        <!-- 云坐席弹窗 -->
        <YunZuoXiDialog ref="yunZuoXiDialogRef" :record="xianYunData" @confirmHelp="confirmHelp" />
        <!-- 健康监测弹窗 -->
        <EmployeeDialog ref="employeeDialogRef" :record="socketData" />
        <!-- 应急、120弹窗 -->
        <EmergencyDialog ref="emergencyDialogRef" :record="emergencyData" @confirmHelp="confirmHelp" />
        <!-- 服务详情数据弹窗 -->
        <PhoneDialog ref="phoneDialogRef" :title="phoneDialogTitle" :useForm="true" :setting="setting" :phoneType="phoneType" />
        <!-- 主诉分类应急工单弹窗-->
        <OrderDialog ref="orderDialogRef" title="应急工单"></OrderDialog>
    </div>
</template>
<script setup lang="ts">
    import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
    import OneL from '/@/components/body-d-left/oneL.vue';
    import TwoL from '/@/components/body-d-left/twoL.vue';
    import ThreeL from '/@/components/body-d-left/threeL.vue';
    import OneR from '/@/components/body-d-right/oneR.vue';
    import TwoR from '/@/components/body-d-right/twoR.vue';
    import ThreeR from '/@/components/body-d-right/threeR.vue';
    import xianMap from '/@/components/xianMap/xianMap.vue';
    import EmployeeDialog from '/@/views/components/employeeDialog.vue';
    import EmergencyDialog from '/@/views/components/emergencyDialog.vue';
    import YunZuoXiDialog from '/@/views/components/yunZuoXiDialog.vue';
    import { useTopTime } from '/@/utils/utils.ts';
    import { basicPath, emergencyPath, xianYunPath, useSocket } from '/@/utils/socket.ts';
    import { useRefresh } from '/@/hooks/autoRefresh';
    import { DEFAULT_TIME } from '/@/hooks/autoRefresh/pageRefreshTime.ts';
    import { DataType, getSettings, ThemeType } from '/@/utils/settings.ts';
    import { ServerDetailType } from '/@/components/body-d-left/bodyLeftHooks.ts';
    import PhoneDialog from '/@/views/components/phoneDialog/phoneDialog.vue';
    import OrderDialog from '/@/views/components/orderDialog.vue';
    import { Map } from '/@/assets/mapUtils/map.ts';
    import { useUserStore } from '/@/store/modules/user.ts';
    import { lightMapOption } from '/@/assets/mapUtils/mapConstant.ts';
    import { useTheme } from '/@/hooks/theme/useTheme.ts';

    const { refreshState } = useRefresh(DEFAULT_TIME);
    const dayTimeO = ref();
    const dayTimeT = ref();
    const interval = ref(1);
    const setting = getSettings(DataType.xian);

    function init() {
        getTime();
        interval.value = setInterval(() => {
            getTime();
        }, 1000);
    }

    function getTime() {
        const { timeLeft, timeRight } = useTopTime();
        dayTimeO.value = timeLeft;
        dayTimeT.value = timeRight;
    }

    const store = useUserStore();
    onMounted(() => {
        init();
        document.addEventListener('visibilitychange', checkTabState);
        //设置主题
        store.setThemeType(ThemeType.light);
    });
    const { themeType } = useTheme();
    onUnmounted(() => {
        clearInterval(interval.value);
        document.removeEventListener('visibilitychange', checkTabState);
    });

    const tabState = ref('');

    //判断窗口是否处于激活状态，切换浏览器tab会导致部分echarts显示不正常
    function checkTabState() {
        tabState.value = document.hidden ? 'inactive' : 'active';
    }

    // 健康监测工具报警
    const { socketData, setSocketData, closeSocket } = useSocket(basicPath + `${DataType.xian}`);
    const employeeDialogRef = ref();

    //模拟开启
    function employeeDialogOpen() {
        setSocketData({
            userId: '001a9878fdaf401c844a03e2fc7c370b',
            realName: '曹燕',
            lon: 108.872442,
            lat: 34.189956,
            sex: 2,
            age: 40,
            orgCode: 'A01A33A05',
            orgName: '地质研究所',
            hospitalList: [
                {
                    id: null,
                    name: '交大一附院',
                    lat: 34.22,
                    lon: 108.94,
                    type: null,
                    ambulance: null,
                    docNum: null,
                    nurseNum: null,
                    expertNum: null,
                    distance: null,
                },
                {
                    id: null,
                    name: '高新医院',
                    lat: 34.23,
                    lon: 108.88,
                    type: null,
                    ambulance: null,
                    docNum: null,
                    nurseNum: null,
                    expertNum: null,
                    distance: null,
                },
                {
                    id: null,
                    name: '人民医院',
                    lat: 34.24,
                    lon: 108.93,
                    type: null,
                    ambulance: null,
                    docNum: null,
                    nurseNum: null,
                    expertNum: null,
                    distance: null,
                },
            ],
        });
        emergencyDialogRef.value.openDialog();
    }

    watch(socketData, (nVal) => {
        if (nVal) {
            nextTick(() => {
                setSocketData(nVal);
                employeeDialogRef.value.openDialog();
            });
        }
    });

    //应急求助、120弹窗
    const { socketData: emergencyData, setSocketData: setEmergencyData, closeSocket: closeSocket2 } = useSocket(emergencyPath + `${DataType.xian}`);
    const emergencyDialogRef = ref();

    watch(emergencyData, (nVal) => {
        if (nVal) {
            nextTick(() => {
                setEmergencyData(nVal);
                emergencyDialogRef.value.openDialog();
            });
        }
    });
    //西安云坐席
    const { socketData: xianYunData, setSocketData: setXianYunData, closeSocket: closeSocket3 } = useSocket(xianYunPath);
    const yunZuoXiDialogRef = ref();
    watch(xianYunData, (nVal) => {
        if (nVal) {
            nextTick(() => {
                setXianYunData(nVal);
                yunZuoXiDialogRef.value.openDialog();
            });
        }
    });

    onUnmounted(() => {
        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeSocket();
            closeSocket2();
            closeSocket3(); //西安云坐席
        };

        clearInterval(interval.value);
    });
    const phoneDialogTitle = ref('呼入电话');
    const phoneDialogRef = ref();
    //0:处置 1:处理 2:呼入 3:全部
    const phoneType = ref('');

    //呼入电话、受理电话弹窗
    function handlePhoneDialog(item) {
        const { name, key } = item;
        //呼入电话
        //受理电话
        if (key == 'alerdyreceive' || key == 'gross') {
            phoneType.value = ServerDetailType[key];
            phoneDialogTitle.value = name;
            nextTick(() => {
                phoneDialogRef.value.openDialog();
            });
        }
    }

    const hospitalList = ref([]); //医院列表
    const showHospitalList = ref(false);

    //确认应急求助
    async function confirmHelp(data) {
        if (!data.lon) return;
        hospitalList.value = [];
        //用户的坐标信息
        let point = [data.lon, data.lat];
        if (data.hospitalList && data.hospitalList.length > 0) {
            try {
                hospitalList.value = await getHospitalList(data.hospitalList, point);
                showHospitalList.value = true;
            } catch (error) {
                console.log('获取医院列表时出错:', error);
            }
        } else {
            console.log('没有医院list');
        }
        Map.getAddressByPoint(point).then((res) => {
            const option = {
                lon: data.lon,
                lat: data.lat,
                position: point,
                name: data.realName,
                address: res,
                sex: data.sex,
            };
            Map.createEmergencyMarker(option);
        });
    }

    async function getHospitalList(hospitalList, userLocation) {
        const hospitalPromises = hospitalList.map(async (item) => {
            item.distance = getDistance(userLocation, [item.lon, item.lat]);
            const { time, routeList } = await getDriveTime(userLocation, [item.lon, item.lat]);
            item.driveTime = time;
            item.routeList = routeList;
            item.userLocation = userLocation;
            return item; // 返回更新后的医院条目
        });
        return Promise.all(hospitalPromises);
    }

    function getDistance(userLocation, destination) {
        const value = Map.getDistance(userLocation, destination);
        return value > 1000 ? (value / 1000).toFixed(2) + 'km' : value + 'm';
    }

    async function getDriveTime(userLocation, destination) {
        let { time, steps } = await Map.getDriveTime(userLocation, destination);
        let h,
            m,
            s = 0;
        if (time <= 60) {
            return {
                time: `${s}秒`,
                routeList: steps,
            };
        }
        if (time > 60 && time < 3600) {
            m = Math.floor(time / 60);
            return {
                time: `${m}分`,
                routeList: steps,
            };
        }
        if (time >= 3600) {
            h = Math.floor(time / 3600);
            m = Math.floor((time - h * 3600) / 60);
            return {
                time: `${h}小时${m}分`,
                routeList: steps,
            };
        }
    }

    function clearHospitalList() {
        hospitalList.value = [];
        showHospitalList.value = false;
    }

    // 地图上绘制
    function test() {
        let nVal = {
            watchNo: 'CRFTQ22C03000080',
            eventType: 'heart_rate',
            bindUserId: 'fd358031299d4816b5d304fd818ecc73',
            createBy: null,
            createDate: null,
            dataValue: '999',
            address:
                '一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字',
            lon: 108.6666,
            lat: 29.8888,
            dataDate: '2023-12-07',
            warnTime: '2023-12-07',
            gpsErrorMsg: '',
            lonGd: 108.67084314886117,
            latGd: 29.88607705672868,
            addressGd: null,
            sendFlag: '0',
            largeScreenFlag: '0',
            orgCode: null,
            orgName: '冯地坑采油作业区',
            realName: '王志文',
            phone: '15229020494',
        };
        nextTick(() => {
            setEmergencyData(nVal);
            emergencyDialogRef.value.openDialog();
        });
    }

    /**
     * 应急单查看详情
     */
    const orderDialogRef = ref(null);

    function viewDetail() {
        orderDialogRef.value.openDialog();
    }
</script>
<style lang="less" scoped>
    .outer {
        height: 100%;
        box-sizing: border-box;
        background: url('/@/assets/images/backgroundNew.png') no-repeat;
        background-size: 100% 100%;
    }

    .title-d {
        height: 80px;
        line-height: 80px;
        display: flex;
        padding-bottom: 9px;
        background-size: 100% 100%;

        .title-d-left,
        .title-d-middle,
        .title-d-right {
            font-size: 27px;
            line-height: 60px;
            text-align: center;
        }

        > :nth-child(1) {
            width: 29%;
        }

        > :nth-child(2) {
            width: 42%;
            font-size: 40px;
            font-weight: bold;
        }

        > :nth-child(3) {
            width: 29%;
        }
    }

    .body-d {
        display: flex;
        height: calc(100% - 120px);
        padding-top: 10px;

        > :nth-child(1) {
            width: 25%;
        }

        > :nth-child(2) {
            width: 50%;
        }

        > :nth-child(3) {
            width: 25%;
        }

        .body-d-left,
        .body-d-right {
            text-align: center;
            display: flex;
            flex-direction: column;

            > div {
                height: calc((100% / 3) - 10px);
                padding: 10px;
            }

            > :nth-child(n + 1) {
                margin-bottom: 10px;
            }
        }

        .body-d-middle {
            display: flex;
            flex-direction: column;
        }
    }

    .bottom-d {
        height: 40px;
        background: url('../assets/images/bottom-b.png') no-repeat;
        background-size: 100% 100%;
    }
</style>
